<template>
  <a-modal
    :title="(model && model.id) ? '编辑商品' : '新增商品'"
    :width="960"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleOK"
    @cancel="() => { $emit('cancel') }">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item label="id" style="display: none;">
          <a-input v-decorator="['id']" />
        </a-form-item>
        <a-form-item label="商品简介">
          <a-input v-decorator="['brief', { rules: [{ required: true, message: '请输入标题' }] }]" />
        </a-form-item>
        <a-form-item label="商品名称">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入标题' }] }]" />
        </a-form-item>
        <a-form-item label="商品主图">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            accept="image/png, image/jpeg"
            :show-upload-list="false"
            :action="uploadApi"
            @change="handleChange"
            v-decorator="[
              'picUrl',
              {
                valuePropName: 'file',
                getValueFromEvent: normFile,
                rules: [{ required: true, message: '请上传图片' }]
              },
            ]">
            <img
              v-if="files.pro && files.pro.length"
              :src="files.pro[0].response.data.src"
              alt="avatar"
              width="120"
              height="80" />
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-icon class="loading" type="loading" v-if="proLoading" />
          <div class="tips">建议尺寸: 45 * 45</div>
        </a-form-item>
        <a-form-item label="商品所属类目ID">
          <a-select
            v-decorator="[
              'categoryId',
              { rules: [{ required: true, message: '请选择' }] }
            ]"
            placeholder="请选择">
            <a-select-option v-for="item in categoryList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属店铺ID">
          <a-select
            v-decorator="[
              'shopsId',
              { rules: [{ required: true, message: '请选择' }] }
            ]"
            placeholder="请选择">
            <a-select-option v-for="item in shopsList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="会员价格/元">
          <a-input v-decorator="['counterPrice', { rules: [{ required: true, message: '请输入标题' }] }]" />
        </a-form-item>
        <a-form-item label="零售价格/元">
          <a-input v-decorator="['retailPrice', { rules: [{ required: true, message: '请输入标题' }] }]" />
        </a-form-item>
        <a-form-item label="商品详细介绍">
          <div class="upload-wrapper">
            <div class="img-list" v-if="files.detail.length > 0">
              <div class="img-item" v-for="(item, index) in files.detail">
                <img class="img" :src="item.response.data.src" alt="avatar" width="690" height="280" />
                <div class="mask">
                  <a-icon class="myicon" type="eye" @click="handlePreview(item)" />
                  <a-icon class="myicon" type="delete" @click="handleDelete(index, 'detail')" />
                </div>
              </div>
            </div>
            <a-upload
              name="file"
              list-type="picture-card"
              accept="image/png, image/jpeg, application/pdf, application/msword, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :show-upload-list="false"
              :action="uploadApi"
              @change="detialChange"
              v-decorator="[
                'detail',
                {
                  valuePropName: 'files',
                  getValueFromEvent: detailFile,
                  rules: [{ required: true, message: '请上传图片' }]
                },
              ]">
              <div class="upload-btn" v-show="!files.detail.length || files.detail.length < 5">
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
          </div>
          <a-icon class="loading" type="loading" v-if="detailLoading" />
        </a-form-item>
        <a-form-item label="商品轮播图">
          <div class="upload-wrapper">
            <div class="img-list" v-if="files.gallery.length > 0">
              <div class="img-item" v-for="(item, index) in files.gallery">
                <img class="img" :src="item.response.data.src" alt="avatar" width="690" height="280" />
                <div class="mask">
                  <a-icon class="myicon" type="eye" @click="handlePreview(item)" />
                  <a-icon class="myicon" type="delete" @click="handleDelete(index, 'gallery')" />
                </div>
              </div>
            </div>
            <a-upload
              name="file"
              list-type="picture-card"
              accept="image/png, image/jpeg, application/pdf, application/msword, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :show-upload-list="false"
              :action="uploadApi"
              @change="galleryChange"
              v-decorator="[
                'gallery',
                {
                  valuePropName: 'files',
                  getValueFromEvent: galleryFile,
                  rules: [{ required: true, message: '请上传图片' }]
                },
              ]">
              <div class="upload-btn" v-show="!files.gallery.length || files.gallery.length < 5">
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
          </div>
          <a-icon class="loading" type="loading" v-if="galleryLoading" />
        </a-form-item>
        <a-form-item label="商品编号">
          <a-input v-decorator="['goodsSn', { rules: [{ required: true, message: '请输入标题' }] }]" />
        </a-form-item>
        <a-form-item label="是否人气推荐">
          <a-radio-group name="isHot" v-decorator="['isHot', { rules: [{ required: true, message: '请选择状态' }] }]">
            <a-radio :value="0">
              否
            </a-radio>
            <a-radio :value="1">
              是
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否新品首发">
          <a-radio-group name="isNew" v-decorator="['isNew', { rules: [{ required: true, message: '请选择状态' }] }]">
            <a-radio :value="0">
              否
            </a-radio>
            <a-radio :value="1">
              是
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否上架">
          <a-radio-group name="radioGroup" v-decorator="['isOnSale', { rules: [{ required: true, message: '请选择状态' }] }]">
            <a-radio :value="0">
              下架
            </a-radio>
            <a-radio :value="1">
              上架
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="排序权重">
          <a-input v-decorator="['sortOrder', { rules: [{ required: true, message: '请输入排序权重' }] }]" />
        </a-form-item>
        <a-form-item label="商品单位">
          <a-input v-decorator="['unit', { rules: [{ required: true, message: '请输入商品单位，例如件、盒' }] }]" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import api from '@/api/banner'
import { goodCategoryList as categoryList, shopsList } from '@/api/shop'
// 表单字段
const fields = ['brief', 'categoryId', 'counterPrice', 'detail', 'id', 'gallery', 'goodsSn', 'isHot', 'isNew', 'isOnSale', 'name', 'picUrl', 'retailPrice', 'shopsId', 'sortOrder', 'unit']
const baseApi = process.env.VUE_APP_API_BASE_URL
// import UploadPreview from '@/components/upload-prevew'
export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
    return {
      form: this.$form.createForm(this),
      files: {
        pro: [],
        detail: [],
        gallery: []
      },
      shopsList: [],
      categoryList: [],
      proLoading: false,
      detailLoading: false,
      galleryLoading: false,
      logoLoading: false,
      uploadApi: baseApi + api.upload
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    this.getCategory()
    this.getShops()
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if (this.model) {
        this.files.pro = [{ response: { data: { src: this.model.picUrl } }, status: 'done', name: this.model.id }] || []
        this.files.detail = this.model.detail.split(',').map(i => { return { response: { data: { src: i } }, status: 'done', name: this.model.id } }) || []
        this.files.gallery = this.model.gallery.split(',').map(i => { return { response: { data: { src: i } }, status: 'done', name: this.model.id } }) || []
        this.form.setFieldsValue(pick(this.model, fields))
        this.content = this.model.content
      }
    })
  },
  methods: {
    async getCategory () {
      const res = await categoryList({ limit: 10000 })
      if (!res.success) return
      this.categoryList = res.data.records
    },
    async getShops () {
      const res = await shopsList({ limit: 10000 })
      if (!res.success) return
      this.shopsList = res.data.records
    },
    normFile (e) {
      if (e.file.response && e.file.response.data) {
        // this.form.setFieldsValue({ srcSave: e.file.response.data.srcSave })
        return e.file.response.data.src
      }
      return ''
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.fileLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.files.pro.push(info.file)
        this.fileLoading = false
      }
    },
    detialChange (info) {
      if (info.file.status === 'uploading') {
        this.detailLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.files.detail.push(info.file)
        this.detailLoading = false
      }
    },
    detailFile () {
      const fileList = this.files.detail
      if (fileList.length > 0) {
        const arr = fileList.map(i => i.response.data.src)
        return arr.join(',')
      } else {
        return ''
      }
    },
    galleryChange (info) {
      if (info.file.status === 'uploading') {
        this.galleryLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.files.gallery.push(info.file)
        this.galleryLoading = false
      }
    },
    galleryFile () {
      const fileList = this.files.gallery
      if (fileList.length > 0) {
        const arr = fileList.map(i => i.response.data.src)
        return arr.join(',')
      } else {
        return ''
      }
    },
    handlePreview (e) {
      window.open(e.response.data.src, '_blank')
    },
    handleDelete (index, type) {
      this.files[type].splice(index, 1)
      const str = type === 'detail' ? this.detailFile() : this.galleryFile()
      this.form.setFieldsValue({ [type]: str })
    },
    handleOK () {
      this.form.validateFields((errors, values) => {
        // console.log(values)
      })
      this.$emit('ok')
    }
  }
}
</script>
<style scoped lang="less">
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.upload-wrapper {
  display: flex;
}

.img-list {
  display: flex;

  .img-item {
    position: relative;
    width: 100px;
    height: 100px;
    padding: 4px;
    overflow: hidden;
    box-sizing: border-box;
    margin-right: 10px;
    border-radius: 10px;
    overflow: hidden;

    &:hover .img-list .img-item .mask {
      display: block;
    }

    .img {
      height: 100%;
      width: 100%;
    }
  }

  .upload-btn {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

  }

  .myicon {
    font-size: 20px;
    color: #fff;

    &:hover {
      color: #1890ff;
    }
  }

  .mask {
    display: none;
    position: absolute;
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, .65);
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
}
</style>
